import axios from 'axios'

export class GuiguRequest{

     instance

     defaultRequestInterceptor={
        requestInterceptor:(config)=>{
            return config
        },
        requestInterceptorCatch:(error)=>{
            return Promise.reject({msg:error.message})
        }
    }

     defaultResponseInterceptor={
        responseInterceptor:response=>{
            return response.data
        },

        responseInterceptorCatch:error=>{
            return Promise.reject({msg:"请求出错"})
        }
    }


    defaultSuccessFn(data){
        return data
    }

    defaultErrorFn(error){
        return Promise.reject(error)
    }
    constructor(config){
        this.instance=axios.create(config)
        this.instance.interceptors.request.use(
            this.defaultRequestInterceptor?.requestInterceptor,
            this.defaultRequestInterceptor?.requestInterceptorCatch
            )
        this.instance.interceptors.response.use(
                this.defaultResponseInterceptor.responseInterceptor,
                this.defaultResponseInterceptor.responseInterceptorCatch
            )
    }
    static  create(config){
        return new GuiguRequest(config)
    }

    post(url,data,params,config){
        if(!config){
            config={

            }
        }
        config.url=url
        config.data=data
        config.params=params
        config.method="post"
        return this.request(config)
    }

    get(url,params,config){
        if(!config){
            config={

            }
        }
        config.url=url
        config.params=params
        config.method="get"
        return this.request(config)
    }

    put(url,data,params,config){
        if(!config){
            config={

            }
        }
        config.url=url
        config.data=data
        config.params=params
        config.method='put'
        return this.request(config)
    }

    delete(url,data,params,config){
        if(!config){
            config={

            }
        }
        config.url=url
        config.data=data
        config.params=params
        config.method='delete'
        return this.request(config)
    }
    request(config){
        return this.instance.request(config)
        .then(this.defaultSuccessFn)
        .catch(this.defaultErrorFn)
    }
}

const config = {
    baseURL:process.env.NUXT_ENV.VITE_BASE_URL,
    timeout: 5000
}

const baseRequest=GuiguRequest.create(config)

export default baseRequest


